package com.my.study.aqs.alternate;

/**
 * @author Carlos
 * @version 1.0.0
 * @date 2023/2/12 19:52
 */
public class WaitNotifyTest {

    public static void main(String[] args) {
        WorkNotify workNotify = new WorkNotify(1, 5);
        
        new Thread(() -> workNotify.print("a", 1, 2)).start();
        new Thread(() -> workNotify.print("b", 2, 3)).start();
        new Thread(() -> workNotify.print("c", 3, 1)).start();

    }
    
}


/**
 * 
 * 输出内容     等待标记      下一个标记
 *    a            1            2
 *    b            2            3
 *    c            3            1
 */
class WorkNotify {
    
    private int flag;
    
    private int loopNum;

    public WorkNotify(int flag, int loopNum) {
        this.flag = flag;
        this.loopNum = loopNum;
    }
    
    public void print(String str, int waitFlag, int nextFlag) {
        for (int i = 0; i < loopNum; i++) {
            synchronized (this) {
                while (flag != waitFlag) {
                    try {
                        // 调用wait()方法，会释放持有的锁
                        this.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.print(str);
                flag = nextFlag;
                this.notifyAll();
            }
        }
    }
}


